import 'package:flutter/material.dart';
import 'package:dio/dio.dart'; // 导入 Dio
import 'package:intl/intl.dart'; // 用于日期格式化

class UpListPage extends StatefulWidget {
  const UpListPage({super.key});

  @override
  State<UpListPage> createState() => _UpListPageState();
}

class _UpListPageState extends State<UpListPage> {
  List<dynamic> _inspections = [];
  bool _isLoading = true;
  String _errorMessage = '';
  final Dio _dio = Dio(); // 创建 Dio 实例

  @override
  void initState() {
    super.initState();
    _fetchInspections();
  }

  Future<void> _fetchInspections() async {
    setState(() {
      _isLoading = true;
      _errorMessage = '';
    });

    const String url = 'http://117.174.116.51:50508/api/education/inspections/page';

    try {
      final response = await _dio.get(
        url,
        data: {
          "pageNum": 1, // 当前页码
          "pageSize": 100, // 每页大小
        },
      );

      if (response.statusCode == 200) {
        final Map<String, dynamic> responseData = response.data;
        if (responseData['success'] == true && responseData['data'] != null) {
          setState(() {
            _inspections = responseData['data']['records'];
            _isLoading = false;
          });
        } else {
          setState(() {
            _errorMessage = responseData['message'] ?? '请求失败：未知错误';
            _isLoading = false;
          });
        }
      } else {
        setState(() {
          _errorMessage = '请求失败，状态码: ${response.statusCode}';
          _isLoading = false;
        });
      }
    } on DioException catch (e) { // 捕获 Dio 异常
      if (e.response != null) {
        _errorMessage = '请求错误: ${e.response?.statusCode} - ${e.response?.statusMessage}';
      } else {
        _errorMessage = '网络错误: $e';
      }
      setState(() {
        _isLoading = false;
      });
    } catch (e) { // 捕获其他未知异常
      setState(() {
        _errorMessage = '发生未知错误: $e';
        _isLoading = false;
      });
    }
  }

  // 辅助函数：格式化日期
  String _formatDateTime(String? dateTimeString) {
    if (dateTimeString == null || dateTimeString.isEmpty) {
      return 'N/A';
    }
    try {
      final dateTime = DateTime.parse(dateTimeString);
      return DateFormat('yyyy-MM-dd HH:mm').format(dateTime);
    } catch (e) {
      return dateTimeString; // 解析失败则返回原始字符串
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF4F9FD),
      appBar: AppBar(
        title: const Text('巡检记录列表',style: TextStyle(color: Colors.black,fontSize: 18,fontWeight: FontWeight.bold)),
        backgroundColor: Colors.white,
        centerTitle: true,
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _errorMessage.isNotEmpty
          ? Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(_errorMessage, textAlign: TextAlign.center),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _fetchInspections,
              child: const Text('重试'),
            ),
          ],
        ),
      )
          : _inspections.isEmpty
          ? const Center(child: Text('暂无巡检记录'))
          : ListView.builder(
        itemCount: _inspections.length,
        itemBuilder: (context, index) {
          final inspection = _inspections[index];
          return Card(
            margin: const EdgeInsets.all(8.0),
            color: Colors.white,
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '姓名: ${inspection['inspectorName'] ?? 'N/A'}',
                    style: const TextStyle(
                        fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 8),
                  Text('位置: ${inspection['inspectionLocation'] ?? 'N/A'}'),
                  Text('设备: ${inspection['inspectionDevice'] ?? 'N/A'}'),
                  Text('内容: ${inspection['inspectionContent'] ?? 'N/A'}'),
                  Text('状态: ${inspection['status'] == 1 ? '有问题' : (inspection['status'] == 2 ? '无问题' : 'N/A')}'),
                  Text('开始时间: ${_formatDateTime(inspection['startDate'])}'),
                  Text('结束时间: ${_formatDateTime(inspection['endDate'])}'),
                ],
              ),
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _fetchInspections,
        tooltip: '刷新数据',
        backgroundColor: Colors.blue,
        child: const Icon(Icons.refresh,color: Colors.white,),
      ),
    );
  }
}